
<template>
  <a-drawer
    :title="title"
    :visible="visible"
    :width="480"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeModal"
  >
    <a-form layout="vertical">
      <a-row :gutter="24" :wrap="true">
        <a-col :span="24">
          <a-form-item label="字段名称" v-bind="validateInfos.fields_name">
            <a-input class="w-100p" v-model:value="formState.fields_name"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item v-bind="validateInfos.sort">
            <template #label>
              <span>字段排序</span>
              <span style="font-size: 12px; color: #999">（数字越大越靠前）</span>
            </template>
            <a-input-number
              class="w-100p"
              placeholder="请输入"
              v-model:value="formState.sort"
              :min="0"
              :precision="0"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item v-bind="validateInfos.village_id">
            <template #label>
              <span>所属项目</span>
              <span style="font-size: 12px; color: #999">（不选择为通用）</span>
            </template>
            <a-select
              v-model:value="formState.village_id"
              show-search
              placeholder="请输入"
              :allowClear="true"
              class="w-100p"
              :options="villageList"
              :filter-option="filterOption"
            ></a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button type="primary" @click.prevent="onSubmit" :loading="submitLoading">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
import {computed, defineComponent, watch, ref, reactive, toRaw, toRefs} from "vue";
import _ from "lodash";
import {Form, message} from "ant-design-vue";
import request from "@/common/utils/request";
const useForm = Form.useForm;

export default defineComponent({
  name: "extraManage",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    }
  },
  components: { },
  setup(props, {emit}) {
    const state = reactive({
      formState: {
        fields_name: '',
        sort: '',
        village_id: undefined,
        // isRequired: 0,
      },
      rulesRef: {
        fields_name: [{ required: true, message: "字段名称必填" }],
      },
      submitLoading: false,
      villageList: [],
    });

    const title = computed(() => {
      return props.id ? "编辑字段" : "添加字段";
    });

    const { resetFields, validate, validateInfos } = useForm(
      state.formState,
      state.rulesRef,
    );
    const closeModal = () => {
      emit("closeModal");
    };

    const onSubmit = () => {
      validate().then(() => {
        state.submitLoading = true;
        if (props?.id) {
          // 编辑
          request.put("/org", "/org/contract/extra/field", {...state.formState, id: props.id}).then((res) => {
            message.success(res?.msg || '保存成功');
            state.submitLoading = false;
            emit('success')
          })
        } else {
          // 添加
          request.post("/org", "/org/contract/extra/field", {...state.formState}).then((res) => {
            message.success(res?.msg || '添加成功');
            state.submitLoading = false;
            emit('success')
          })
        }
      });
    };


    const setModelRef = (info) => {
      for (let key in state.formState) {
        if (key == 'village_id') {
          state.formState[key] = info[key] || undefined;
        } else {
          state.formState[key] = info[key];
        }
      }
    };

    const getVillageList = () => {
      request
        .get("/org", "/build/villageAndBuildList/v2", {
          checked: 1,
        })
        .then((res) => {
          let vList = [];
          (res.villageList || []).forEach((item) => {
            vList.push({
              label: item.name,
              value: item.id,
            });
          });
          state.villageList = vList;
        });
    };

    const filterOption = (input, option) => {
      return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };

    const init = () => {
      getVillageList();
      if (props.id) {
        // 编辑
        request.get("/org", `/org/contract/extra/field/${props.id}`).then((res) => {
          const { detail } = res;
          setModelRef(detail);
        })
      }
    };
    const reset = () => {
      resetFields();
      state.submitLoading = false;
      state.villageList = [];
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          reset();
        }
      }
    );
    return {
      ...toRefs(state),
      validateInfos,
      title,
      closeModal,
      onSubmit,
      filterOption,
    };
  },
});
</script>
<style lang="less" scoped>

</style>
